<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.schoolName" clearable class="filter-item" style="width: 200px;" placeholder="请输入学校名称"/>
      <el-button v-permission="['GET /admin/shop/list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['POST /admin/shop/create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column align="center" width="60px" label="ID" prop="id" sortable/>

      <el-table-column align="center" label="学校图片" prop="schoolUrl">
        <template slot-scope="scope">
          <img v-if="scope.row.schoolUrl" :src="scope.row.schoolUrl" width="80">
        </template>
      </el-table-column>

      <el-table-column align="center" label="学校名称" prop="schoolName"/>

      <el-table-column align="center" label="学校地址" prop="schoolAddress"/>

      <el-table-column align="center" width="200" label="学校配送状态" prop="payOff">
        <template slot-scope="scope">
          <el-switch @change="handleSettingChange(scope.row)"
            v-model="scope.row.payOff==1?false:true"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="上楼"
            inactive-text="自取">
          </el-switch>
        </template>
      </el-table-column>
      <!--
      <el-table-column align="center" label="联系人" prop="adminId"/>-->

      <el-table-column align="center" label="号码" prop="phone"/>

      <el-table-column align="center" label="地理位置" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button  round size="default">{{scope.row.longitude}}</el-button>
          <span> - </span>
          <el-button  round size="default">{{scope.row.latitude}}</el-button>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['POST /admin/school/update']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['POST /admin/shop/delete']" type="success" plain size="mini" @click="handleschoolsetting(scope.row)">设置</el-button>
          <!--
          <el-button v-permission="['POST /admin/shop/delete']" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />


    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="学校名称" prop="schoolName">
          <el-input v-model="dataForm.schoolName"/>
        </el-form-item>
        <el-form-item label="学校地址" prop="schoolAddress">
          <el-input v-model="dataForm.schoolAddress"/>
        </el-form-item>
        <!--
        <el-form-item label="负责人" prop="adminId">
          <el-select v-model="dataForm.adminId" clearable>
            <el-option v-for="item in listAdmin" :key="item.username" :label="item.username" :value="item.id" />
          </el-select>
        </el-form-item>-->
        <el-form-item label="负责人号码" prop="phone">
          <el-input v-model="dataForm.phone"/>
        </el-form-item>
        <el-form-item label="地理坐标" prop="longitude">
          <el-col :span="11" >
            <el-input v-model="dataForm.longitude" placeholder="经度"/>
          </el-col>
          <el-col :span="2" style="text-align: center;">-</el-col>
          <el-col :span="11">
            <el-input v-model="dataForm.latitude" placeholder="纬度"/>
          </el-col>
        </el-form-item>
        <el-form-item label="学校图片" prop="schoolUrl">
          <el-upload
            :headers="headers"
            :action="uploadPath"
            :show-file-list="false"
            :on-success="uploadUrl"
            :before-upload="checkFileSize"
            class="avatar-uploader"
            accept=".jpg,.jpeg,.png,.gif">
            <img v-if="dataForm.schoolUrl" :src="dataForm.schoolUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1024kb</div>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

    <!-- 学校设置-->
    <el-dialog :visible.sync="schoolsetting" title="设置">
      <!--
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange" >
          <el-checkbox v-for="item in listShop" :label="item.shopName" :key="item.shopName" :value="item.id"></el-checkbox>
        </el-checkbox-group>
        <el-checkbox-group v-model="dataForm.shopIds" @change="handleCheckedCitiesChange" >
          <el-checkbox v-for="item in listShop" :label="item.id" :key="item.id" :value="item.id" >{{item.shopName}}</el-checkbox>
        </el-checkbox-group>-->

        <el-transfer
              @change="handleChange"
              filterable
              filter-placeholder="搜索商家"
              :titles="['待选商家', '已选商家']"
              :button-texts="['移除', '添加']"
              :left-default-checked="[1,2]"
              :right-default-checked="checkedIds"
              v-model="dataForm.shopIds" :data="listShop"></el-transfer>
        <!--
          <el-select style="min-width: 500px;"
            size="300"
            v-model="checkedCities"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择店铺">
            <el-option
              v-for="item in listShop"
              :key="item.shopName"
              :label="item.shopName"
              :value="item.id">
            </el-option>
          </el-select>
          <el-form-item label="管理员角色" >
            <el-select v-model="dataForm.shopIds" multiple placeholder="请选择">
              <el-option
                v-for="item in listShop"
                :key="item.shopName"
                :label="item.shopName"
                :value="item.id"/>
            </el-select>
          </el-form-item>-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="schoolsetting = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>



<script>
import { listSchool, createSchool, updateSchool, deleteSchool, listAdmin, listShop, listShopIds } from '@/api/school'
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'Ad',
  components: { Pagination },
  data() {
    return {
      uploadPath,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        schoolName: undefined
      },
      dataForm: {
        id: undefined,
        adminId: undefined,
        schoolName: undefined,
        schoolAddress: undefined,
        phone: undefined,
        latitude: undefined,
        longitude: undefined,
        schoolUrl: undefined,
        shopIds: [],
        payOff: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        schoolName: [{ required: true, message: '学校名称不能为空', trigger: 'blur' }],
        schoolAddress: [{ required: true, message: '学校地址不能为空', trigger: 'blur' }],
        phone: [{ required: true, message: '联系人号码不能为空', trigger: 'blur' }],
        schoolUrl: [{ required: true, message: '学校图片不能为空', trigger: 'blur' }],
        adminId: [{ required: true, message: '请选择负责人', trigger: 'blur' }],
        longitude: [{ required: true, message: '请填写经纬度', trigger: 'blur' }]
      },
      downloadLoading: false,
      schoolsetting: false,
      isIndeterminate: true,
      checkAll: false,
      checkedCities: [],
      listAdmin: {},
      listShop: [],
      shopIdss: [],
      checkedIds: []

    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      listSchool(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
      handleSettingChange(row) {
        //console.log(value, direction, movedKeys);
        var off = 0;
        if(row.payOff == 0){
            off = 1;
        }
        this.dataForm = row
        this.dataForm.payOff = off

        //this.dataForm.shopIds = this.checkedIds

        updateSchool(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新门店成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })


      },
    //添加商户
    handleChange(value, direction, movedKeys) {
        //console.log(value, direction, movedKeys);
        //console.log(this.shopIdss);
        this.checkedIds.push(value.length)
        //console.log(this.checkedIds);
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        adminId: undefined,
        schoolName: undefined,
        schoolAddress: undefined,
        phone: undefined,
        latitude: undefined,
        longitude: undefined,
        schoolUrl: undefined,
        shopIds: []
      }
    },

    handleCheckAllChange(val) {
      this.checkedCities = val ? this.listShop:[];
      this.isIndeterminate = false;
    },

    handleCheckedCitiesChange(value) {
      console.log(value);
      console.log(this.checkedCities);

      /*
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.listShop.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.listShop.length;
      let index = 0;
      if(checkedCount > 0){
        index = value.length-1
      }
      let ids = this.listShop[checkedCount-1].id;
      this.dataForm.shopIds.push(ids)*/
    },

    handleSubmit(){
      //this.dataForm.shopIds = this.checkedCities
      updateSchool(this.dataForm)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '设置成功'
          })
          this.getList()
          this.schoolsetting = false
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
    },
    handleschoolsetting(row){
      this.dataForm.id = row.id
      this.dataForm.shopIds = []
      this.listShop = []
      //this.checkedCities = []
      this.schoolsetting = true
      this.dataForm = Object.assign({}, row)
      this.getShopIds()
      this.getShop()

      //this.checkedCities = this.dataForm.shopIds

    },

    getShopIds(){
      listShopIds(this.dataForm)
        .then(response => {
          this.dataForm.shopIds = response.data.data
        })
    },
    handleCreate() {
      //this.getAdmin()
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /*
    getAdmin() {
      listAdmin()
        .then(response => {
          this.listAdmin = response.data.data.list
        })
    },*/
    getShop(){
      listShop()
        .then(response => {
          this.listShop = response.data.data.list
        })
    },

    uploadUrl: function(response) {
      this.dataForm.schoolUrl = response.data.url
    },
    checkFileSize: function(file) {
      if (file.size > 2097152) {//2M 2097152
        this.$message.error(`${file.name}文件大于1024KB，请选择小于1024KB大小的图片`)
        return false
      }
      return true
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createSchool(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      //this.getAdmin()
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateSchool(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新门店成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleDelete(row) {
      deleteSchool(row)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '删除成功'
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          'ID',
          '学校名称',
          '学校地址',
          '联系人',
          '号码',
          '经纬度',
          '经纬度'
        ]
        const filterVal = [
          'id',
          'schoolName',
          'schoolAddress',
          'adminId',
          'phone',
          'longitude',
          'latitude'
        ]
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '学校信息')
        this.downloadLoading = false
      })
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>
